class HttpRequest {
    url;
    method;
    #xhr;
    #promise;
    constructor(url, method) {
        this.#xhr = new XMLHttpRequest();
        this.url = url;
        this.method = method;
    }

    send(data) {
        this.#promise = new Promise((resolve, reject) => {
            this.#xhr.onreadystatechange = () => {
                if (this.#xhr.readyState === 4) {
                    if ([200, 204, 205].includes(this.#xhr.status)) {
                        resolve(JSON.parse(this.#xhr.responseText)); // 返回响应数据
                    } else {
                        reject(`Request failed with status ${this.#xhr.status}`, this.#xhr.responseText !== '' ? JSON.parse(this.#xhr.responseText) : '');
                    }
                }
            }
            this.#xhr.open(this.method, this.url, true);
            this.#xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
            //增加一个ajax头部
            this.#xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
            this.#xhr.send((this.params(data)));
        });
        return this;
    }

    success(callback = () => {}){
        this.#promise.then((response) => {
            switch (response.code){
                case 1001:
                    showNotifyCompilation(response.msg || '登录失效了, 请重新登录!', response.code || 1001, response.url.url, response.url.highest);
                    break;
                default :
                    response.msg && showNotifyCompilation(response.msg, response.code || 500, response.url.url, response.url.highest);
            }
            this.#promise.then(callback(response));
        });
        return this;
    }

    error(callback = () => {}){
        this.#promise.catch((msg, error) => {
            showNotifyCompilation('服务器错误：' + msg, 500);
            callback(error);
        });
    }

    params(data) {
        let params = '';
        switch (typeof data){
            case 'object':
                if(Object.keys(data).length > 0){
                    for (let key in data) {
                        params += data[key] instanceof Array ? this.arrayParam(key, data[key]) : `${key}=${data[key]}&`;
                    }
                    params = params.slice(0, -1);
                }
                break;
            case 'string':
                params = data;
                break;
            default:
                params = '';
        }
        return params;
    }

    arrayParam(paramName, data) {
        //判断是否为数组
        if(data instanceof Array){
            let params = '';
            for (let i = 0; i < data.length; i++) {
                params += `${paramName}[]=${data[i]}&`;
            }
            return params;
        }
        return data;
    }
}
